<?php
date_default_timezone_set('Asia/Ho_Chi_Minh'); // dat gio VietNam
// echo date("m-d-y h:m:s"); exit();
// xu ly phan session 
session_start(); // khoi dong session len
$path_root = $_SERVER['DOCUMENT_ROOT']; // C:/xampp/htdocs
// require_once($path_root."/AppSaleOnline/model/user.php");
require_once($path_root."/AppSaleOnline/model/application.php");

$obj_app = new Applications(); // tao doi tuong
// phan du lieu can phai insert vao bang
$user_id  = $_SESSION['user_id'];
$app_id   = $_SESSION['app_id']; 
$time_obj = date("y-m-d h:m:s");

if($obj_app->insert_into_app_user_table($app_id, $user_id, $time_obj) == true)
    echo "insert ok"; // cho phep download
// echo "<a href='?file=appstore.sql'>Download</a>";

//các file upload du?c d? trong 1 thu m?c riêng
$upload_dir = "../store/";
 
//l?y tên file c?n download t? URL
$filename = isset($_GET['file']) ? $_GET['file'] : null;

// var_dump($filename);

//th?c hi?n quá trình ki?m tra
if ( !preg_match('/^[a-z0-9\_\-][a-z0-9\_\-\. ]*$/i', $filename) 
        || !is_file($upload_dir.$filename) || !is_readable($upload_dir.$filename) ) {
    echo "Loi: Ten file khong hop le hoac file khong ton tai!";
    exit(-1);
} //end if
 
// đọc file nhị phân
$fp = fopen($upload_dir.$filename, "rb");
 
//g?i header d?n cho browser
header('Content-type: application/octet-stream');
header('Content-disposition: attachment; filename="'.$filename.'"'); // cho biet ten file va phan mo rong cua no
header('Content-length: ' . filesize($upload_dir.$filename));
 
//đọc file và trả dữ liệu cho browser
fpassthru($fp); // <=> $content = fread($handle, filesize($filename)); echo $content;

fclose($fp);

// tang lượt download lên 

if($obj_app->increase_number_download($filename) == true){    
        echo "Success";
}
